package com.nowcoder.community.controller;

import com.nowcoder.community.contant.Entity;
import com.nowcoder.community.annotation.LoginRequired;
import com.nowcoder.community.contant.Topic;
import com.nowcoder.community.entity.Comment;
import com.nowcoder.community.entity.DiscussPost;
import com.nowcoder.community.entity.Event;
import com.nowcoder.community.event.EventProducer;
import com.nowcoder.community.service.CommentService;
import com.nowcoder.community.service.DisccusPostService;
import com.nowcoder.community.utils.HostHolder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/comment")
public class CommentController {

    @Autowired
    private CommentService commentService;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private EventProducer eventProducer;

    @Autowired
    private DisccusPostService disccusPostService;

    @PostMapping("/add/{discussPostId}")
    @LoginRequired
    public String addComment(@PathVariable int discussPostId, Comment comment, Model model){
        if (StringUtils.isBlank(comment.getContent())){
            model.addAttribute("commentMsg", "评论内容不能为空");
            return "redirect:/discuss/detail/" + discussPostId;
        }
        if (comment.getEntityType() == Entity.DISCUSS_POST && comment.getTargetId() != 0){
            model.addAttribute("commentMsg", "帖子评论不能有回复对象");
            return "redirect:/discuss/detail/" + discussPostId;
        }
        // 添加评论
        comment.setUserId(hostHolder.getUser().getId());
        commentService.addComment(comment);

        // 系统通知
        Event event = new Event()
                .setTopic(Topic.COMMENT)
                .setUserId(hostHolder.getUser().getId())
                .setEntityType(comment.getEntityType())
                .setEntityId(comment.getEntityId())
                .setData("postId", discussPostId);

        if (comment.getEntityType() == Entity.DISCUSS_POST){
            DiscussPost post = disccusPostService.findDiscussPostById(discussPostId);
            event.setEntityUserId(post.getUserId());
            // 更新帖子分数
            disccusPostService.refreshScore(post.getId());
        }else if (comment.getEntityType() == Entity.COMMENT){
            event.setEntityUserId(comment.getTargetId());
        }
        eventProducer.fireEvent(event);


        return "redirect:/discuss/detail/" + discussPostId;
    }
}
